//
//  FRouter.swift
//  FMiddleLevel
//
//  Created by FanQiLe on 2021/7/2.
//

import UIKit

public struct FRouterModel:Codable {
    public var moduleKey:String?
    public var json:String?
}


public class FRouter: NSObject {
    static let manager:FRouter = FRouter()
    var moduleDic:[String:String] = [:]
    
    static public func openActionUrl(url:String) {

        let tempDic = url.stringToDic()
        let moduleKey = tempDic?["moduleKey"] as? String ?? ""
        let name = tempDic?["name"] as? String ?? ""
        if moduleKey.count > 0 {
            var model = FRouterModel()
            model.moduleKey = moduleKey
            model.json = tempDic?["json"] as? String
            FRouter.openAction(model: model)
            return
        } else if name.count > 0 {
            if FRouter.manager.moduleDic.count > 0 {
                let moduleKey: String = FRouter.manager.moduleDic[name] ?? ""
                var model = FRouterModel()
                model.moduleKey = moduleKey
                model.json = url
                FRouter.openAction(model: model,defaultKeyName: moduleKey)
            } else {
                FRegisterHandler.readDataFromMachO { (dic) in
                    print("dic = \(dic)")
                    FRouter.manager.moduleDic = dic ?? [:]
                    FRouter.openActionUrl(url: url)
                }
            }
        }
    }
    
    static public func openAction(model:FRouterModel,defaultKeyName:String = "") {
        var keyName = "KC" + (model.moduleKey ?? "") + "Protocol"
        if defaultKeyName.count > 0 {
            keyName = defaultKeyName
        }
        var tempModel = model
        tempModel.moduleKey = keyName
        let temp = ModuleManager.get(key: keyName)
        if let tempObj = temp as? FRouterProtocol  {
            tempObj.openAction(model:tempModel)
        }
    }
    
}

public extension String {
    // MARK: 字符串转字典
    func stringToDic() -> [String : Any]?{
        guard let data = self.data(using: String.Encoding.utf8),
        let dict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] else {
            return nil
        }
        return dict
    }
}
